import json
import time
import random
import datetime
import requests
from requests.exceptions import ConnectionError
import win32api, win32con
from xhsapi import XhsApi
from Request import RequestNew
from xhs_tcp import CookieApp, XhsTcp
import config
from adsl import ADSL
from xhsapi690 import XHS660 as XHS690
# from Sms import Sms
# import redis

from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor


class XhsShixin(object):
    def __init__(self, remote_computer_name):
        # if not remote_computer_name:
        #     exit("没传远程设备名称")
        self.to_userid_list = []
        self.cid = config.CID
        self.t = config.t      # 注册账号类型, 1表示用手机号 2表示用微博账号
        self.machine_num = config.machine_num
        self.request = RequestNew(remote_computer_name)
        self.request.base_url = config.custorm_base_url
        self.current_ip = self.request.get_current_ip()
        self.xhsapi = XhsApi(self.cid)
        self.xhsapi_690 = XHS690()
        self.adsl_obj = ADSL()
        self.switch_ip()
        # self.init_devices()
        # return

        # if remote_computer_name == "jsxz.sypptp.com:20381":
        #     self.init_devices()
        #     return
        # print("============设备初始化完毕===========")
        # exit()

        now = datetime.datetime.now()
        hour = int(now.strftime("%H"))
        # if 6 <= hour < 24:  # 只在6 - 23 点收发私信
        if 1:  # 只在6 - 23 点收发私信
            machine_list = self.request.get_machine_list()
            print("machine_list -->", machine_list)
            if not(machine_list and len(machine_list) > 0):
                print("当前无任务, 休息5秒")
                time.sleep(5)
                return

            random.shuffle(machine_list)

            init_time = time.time()
            start_time = time.time()
            for index, machine_name in enumerate(machine_list, start=1):
                print("上次运行时间", time.time() - start_time, "     总运行时长: ", time.time() - init_time)
                start_time = time.time()
                print("总设备数 --> {machine_list_len}  当前第{index}个".format(machine_list_len=len(machine_list), index=index))
                print('machine_name -->', machine_name)
                # machine_name = "1598574594818"
                if self.request.check_login_xhs(machine_name):  # 已登录
                    # print("上次运行时间222222222222222222222", time.time() - start_time)
                    self.init_xhsapi()
                    get_new_msg_flag = True
                    flag_send = True
                    while True:
                        flag_send = self.send_msg(machine_name)
                        if not flag_send:
                            break
                        elif type(flag_send) == str and "超过" in flag_send:
                            get_new_msg_flag = False
                            break
                    flag_get = False
                    if get_new_msg_flag:
                        # print("上次运行时间33333333333333333333333333", time.time() - start_time)
                        flag_get = self.get_new_msg(machine_name)
                        # print("上次运行时间444444444444444444444", time.time() - start_time)

                    if flag_send or flag_get:
                        self.switch_ip()

    def init_xhsapi(self):
        self.xhsapi = XhsApi(self.cid)

    def switch_ip(self):
        if "test" in config.RemoteComputerName and config.debug:
            win32api.keybd_event(121, 0, 0, 0)
            win32api.keybd_event(121, 0, win32con.KEYEVENTF_KEYUP, 0)
            print("当前为调试模式,et换ip")
            self.sleep_random()
            while True:
                try:
                    current_ip = self.request.get_current_ip()
                    print("当前ip: ", current_ip)
                    if current_ip != '123.114.200.165':
                        break
                except Exception as e:
                    print('e -->', e)
                    pass
                time.sleep(1)

        else:
            old_ip = self.request.get_current_ip()

            self.adsl_obj.disconnect()
            while True:
                time.sleep(0.2)
                current_ip = self.request.get_current_ip()
                if old_ip != current_ip:
                    print("当前ip: ", current_ip)
                    break
                else:
                    print("等待ip切换: ", old_ip)
            # time.sleep(5)
            # self.adsl_obj.reconnect()
            # print("当前ip: ", self.request.get_current_ip())

        #
        # n = 1
        # while True:
        #     try:
        #         current_ip = self.request.get_current_ip()
        #         if current_ip != self.current_ip:
        #             print("当前ip: ", current_ip)
        #             break
        #         else:
        #             n += 1
        #             if n > 50:
        #                 win32api.keybd_event(121, 0, 0, 0)
        #                 win32api.keybd_event(121, 0, win32con.KEYEVENTF_KEYUP, 0)
        #                 time.sleep(5)
        #         time.sleep(2)
        #     except requests.exceptions.ConnectionError as e:
        #         print('e -->', e)

    # 休息随机秒
    def sleep_random(self, t1=0, t2=0):
        if t1 > 0 and t2 > 0:
            sleep_time = random.random() + random.randint(t1, t2)
        elif t1 > 0:
            sleep_time = t1
        else:
            sleep_time = random.random() + random.randint(1, 2)
        print(str(datetime.datetime.now()) + "   休息随机秒 %s" % sleep_time)
        time.sleep(sleep_time)

    # 登录小红书
    def login(self, machine_name):
        print("get_current_ip -->", self.request.get_current_ip())
        print('machine_name -->', machine_name)

        self.switch_ip()
        if self.t == 1:
            # self.xhs_login_phone(machine_name)
            pass
        else:
            self.xhs_login(machine_name)
            # self.xhs_login_phone(machine_name)
            # self.xhs_login_ck(machine_name)

    # 初始化设备
    def init_devices(self):
        while True:
            machine_list = self.request.get_machine_list()
            print("当前设备数:", len(machine_list))
            if len(machine_list) < self.machine_num:
                self.create_devices()
            else:
                break
        # 检测账号是否登录
        machine_list = self.request.get_machine_list()
        random.shuffle(machine_list)
        for machine_name in machine_list:
            if not self.request.check_login_xhs(machine_name):  # 未登录
                if config.debug:
                    self.login(machine_name)
                    exit()
                else:
                    try:
                        self.login(machine_name)
                    except TypeError as e:
                        print('e -->', e)
                        if 'NoneType' in str(e):
                            continue
                        exit()
                    except ConnectionError as e:
                        continue


                # time.sleep(10)
                # exit()

    # 创建新设备
    def create_devices(self):
        print("创建新设备")
        name = str(int(time.time() * 1000))
        self.request.init(name)
        # self.request.get_wb_user(name)
        self.request.check_login_xhs(name, config.RemoteComputerName)

    # # 获取手机号
    # def get_phonenum(self):
    #     redis_obj = redis.StrictRedis(
    #         host=config.redisServer,
    #         port=1111,
    #         db=13,
    #         decode_responses=True,
    #         password="Fmsuh1J50R%T*Lq15TL#IkWb#oMp^@0OYzx5Q2CSEEs$v9dd*mnqRFByoeGZ"
    #     )
    #
    #     while True:
    #         phonenum = redis_obj.rpop("XHS::XIANSUO::LIST::PHONENUM")
    #         if phonenum:
    #
    #             return phonenum
    #         else:
    #             redis_obj.lpush("XHS::XIANSUO::LIST::PHONENUM::SIGNAL", 1)
    #             print("无可用手机号,发送信号获取")
    #             time.sleep(5)

    # # 获取小红书ck
    # def get_xhs_user_ck(self):
    #     redis_obj = redis.StrictRedis(
    #         host=config.redisServer,
    #         port=1111,
    #         db=13,
    #         decode_responses=True,
    #         password="Fmsuh1J50R%T*Lq15TL#IkWb#oMp^@0OYzx5Q2CSEEs$v9dd*mnqRFByoeGZ"
    #     )
    #
    #     redis_key = "XHS::XIANSUO::LIST::USER_CK"
    #     ck_data = redis_obj.rpop(redis_key)
    #     return ck_data
    #
    #     # while True:
    #     #     phonenum = redis_obj.rpop("XHS::XIANSUO::LIST::PHONENUM")
    #     #     if phonenum:
    #     #
    #     #         return phonenum
    #     #     else:
    #     #         redis_obj.lpush("XHS::XIANSUO::LIST::PHONENUM::SIGNAL", 1)
    #     #         print("无可用手机号,发送信号获取")
    #     #         time.sleep(5)

    # def get_code(self, phonenum):
    #
    #     redis_obj = redis.StrictRedis(
    #         host=config.redisServer,
    #         port=1111,
    #         db=13,
    #         decode_responses=True,
    #         password="Fmsuh1J50R%T*Lq15TL#IkWb#oMp^@0OYzx5Q2CSEEs$v9dd*mnqRFByoeGZ"
    #     )
    #     redis_key = "XHS::XIANSUO::HASH::PHONENUM"
    #     redis_obj.hset(redis_key, phonenum, time.time())
    #
    #     redis_key = "XHS::XIANSUO::KEY::PHONENUM::{phonenum}".format(phonenum=phonenum)
    #     while True:
    #         code = redis_obj.get(redis_key)
    #         if code:
    #             redis_obj.delete(redis_key)
    #             return code
    #         else:
    #             time.sleep(0.5)

    #
    def xhs_login_phone(self, machine_name, phonenum=""):
        result_data = {
            'blogger_id': '',
            'blogger_name': '',
            'blogger_img': '',
            'device_data': '',
        }
        self.init_xhsapi()
        self.xhsapi.init_new_device_params()
        register_smid_ret = self.xhsapi.register_smid()
        print('register_smid_ret:' + register_smid_ret)

        smid = json.loads(register_smid_ret)['detail']['deviceId']
        print('smid:' + smid)
        self.xhsapi.set_smid(smid)

        # 激活用户
        active_user_ret = self.xhsapi.active_user()
        print('active_user_ret:' + active_user_ret)
        success = json.loads(active_user_ret)['success']
        if not success:
            crypt_method = json.loads(active_user_ret)['crypt_method']
            print('crypt_method: ' + crypt_method)
            self.xhsapi.set_crypt_method(crypt_method)

        active_user_ret = self.xhsapi.active_user()
        print('active_user_ret:' + active_user_ret)

        # if 'data' not in json.loads(active_user_ret):
        #     return False

        # 设置session id
        session_id = ''
        active_json = json.loads(active_user_ret)
        if 'data' in active_json:
            session_id = active_json['data']['session']
            print('session_id:' + session_id)

            # 短信验证码登录
            # if len(session_id) == 0:
            if session_id:
                # print("需要短信验证,退出")
                # exit()
                # 发送短信验证码
                # phone = '13903810993'
                phonenum = input("请输入手机号:")
                # sms_obj = Sms()
                # sms_obj.login()
                # if not phonenum:
                #     while True:
                #         phonenum = self.get_phonenum()
                #         if not phonenum.startswith("171") and not self.request.check_phone_exit(phonenum):  # 并且该手机号未使用
                #             break

                send_code_ret = self.xhsapi.send_sms_code(phonenum)
                print('send_code_ret:' + send_code_ret)
                if "超过" in send_code_ret or not json.loads(send_code_ret)['success']:
                    return json.loads(send_code_ret)['msg']

                sms_code = input("验证码:")

                # n = 0
                # while True:
                #     n += 1
                    # time.sleep(5)

                    # sms_code = self.get_code(phonenum)
                    # if "您的验证码是" in sms_code:
                    #     sms_code = sms_code.split(":")[1].split('，')[0].strip()
                    #     break
                    # print('sms_code:' + sms_code)

                    # if n > 10:
                    #     print("未获取到验证码,退出")
                    #     return

                # sms_code = input('请输入短信验证码：')
                print('sms_code:' + sms_code)

                # 验证短信验证码
                check_code_ret = self.xhsapi.check_sms_code(phonenum, sms_code)
                print('check_code_ret:' + check_code_ret)

                # 用短信验证码登录
                mobile_token = json.loads(check_code_ret)['data']['token']
                print('mobile_token:' + mobile_token)
                while True:
                    try:
                        result_data = self.xhsapi.login_with_sms(phonenum, mobile_token)
                        session_id = result_data['session']
                        blogger_id = result_data['userid']
                        blogger_name = result_data['nickname']
                        blogger_img = result_data['images']
                        register_time = result_data['register_time']
                        print('session_id:' + session_id)

                        if len(session_id) == 0:
                            print('session is empty, exit!')
                            exit()

                        # 设置session_id
                        self.xhsapi.set_session_id(session_id)

                        # 获取首页推荐
                        home_feed = self.xhsapi.get_home_feed()
                        print('home_feed:' + home_feed)
                        try:
                            to_userid = json.loads(home_feed)['data'][0]['user']['userid']
                            print('to_userid -->', to_userid)
                        except Exception:
                            return

                        # 获取用户信息
                        # user_info = xhsapi.get_user_info('5c3fe348000000000603daaf')
                        # print('user_info:' + user_info)

                        print(self.xhsapi.get_register_user_data())
                        device_data = self.xhsapi.get_register_user_data()
                        device_data['phone'] = phonenum
                        device_data['register_time'] = register_time
                        # send_msg(device_data, blogger_id, blogger_name, blogger_img, to_userid)

                        ck_data = {'blogger_data': [], 'device_data': device_data, 'blogger_id': blogger_id}
                        userid = ck_data['blogger_id']
                        sid = ck_data['device_data']['sid']
                        device_id = ck_data['device_data']['device_id']
                        smid = ck_data['device_data']['smid']

                        # to_userid = "5c3fe348000000000603daaf"
                        emoji_list = [
                            {
                            'label': 'r_weixiao',
                            'value': '[微笑R]'
                        },
                            {
                                'label': 'haixiu',
                                'value': '[害羞R]'
                            },
                            {
                                'label': 'r_shiwang',
                                'value': '[失望R]'
                            },
                            {
                                'label': 'hanyan',
                                'value': '[汗颜R]'
                            },
                            {
                                'label': 'r_wa',
                                'value': '[哇R]'
                            },
                            {
                                'label': 'r_henaicha',
                                'value': '[喝奶茶R]'
                            },
                            {
                                'label': 'r_zipai',
                                'value': '[自拍R]'
                            },
                            {
                                'label': 'touxiao',
                                'value': '[偷笑R]'
                            },
                            {
                                'label': 'feiwen',
                                'value': '[飞吻R]'
                            },
                            {
                                'label': 'r_shihua',
                                'value': '[石化R]'
                            },
                            {
                                'label': 'xiaoku',
                                'value': '[笑哭R]'
                            },
                            {
                                'label': 'zan',
                                'value': '[赞R]'
                            },
                            {
                                'label': 'r_anzhongguancha',
                                'value': '[暗中观察R]'
                            },
                            {
                                'label': 'r_maibao',
                                'value': '[买爆R]'
                            },
                            {
                                'label': 'r_daxiao',
                                'value': '[大笑R]'
                            },
                            {
                                'label': 'sese',
                                'value': '[色色R]'
                            },
                            {
                                'label': 'shengqi',
                                'value': '[生气R]'
                            },
                            {
                                'label': 'kure',
                                'value': '[哭惹R]'
                            },
                            {
                                'label': 'mengmengda',
                                'value': '[萌萌哒R]'
                            },
                            {
                                'label': 'r_xieyan',
                                'value': '[斜眼R]'
                            },
                            {
                                'label': 'r_kelian',
                                'value': '[可怜R]'
                            },
                            {
                                'label': 'bishi',
                                'value': '[鄙视R]'
                            },
                            {
                                'label': 'r_zhoumei',
                                'value': '[皱眉R]'
                            },
                            {
                                'label': 'zhuakuang',
                                'value': '[抓狂R]'
                            },
                            {
                                'label': 'r_wulian',
                                'value': '[捂脸R]'
                            },
                            {
                                'label': 'r_paidui',
                                'value': '[派对R]'
                            },
                            {
                                'label': 'baji',
                                'value': '[吧唧R]'
                            },
                            {
                                'label': 'jingkong',
                                'value': '[惊恐R]'
                            },
                            {
                                'label': 'r_koubi',
                                'value': '[抠鼻R]'
                            },
                            {
                                'label': 'zaijian',
                                'value': '[再见R]'
                            },
                            {
                                'label': 'tanqi',
                                'value': '[叹气R]'
                            },
                            {
                                'label': 'r_shuijiao',
                                'value': '[睡觉R]'
                            },
                            {
                                'label': 'deyi',
                                'value': '[得意R]'
                            },
                            {
                                'label': 'r_chigua',
                                'value': '[吃瓜R]'
                            },
                            {
                                'label': 'fuqiang',
                                'value': '[扶墙R]'
                            },
                            {
                                'label': 'r_heishuwenhao',
                                'value': '[黑薯问号R]'
                            },
                            {
                                'label': 'r_huangjinshu',
                                'value': '[黄金薯R]'
                            },
                            {
                                'label': 'h_tushetou',
                                'value': '[吐舌头H]'
                            },
                            {
                                'label': 'h_chelian',
                                'value': '[扯脸H]'
                            },
                            {
                                'label': 'h_jingxia',
                                'value': '[惊吓H]'
                            }
                        ]
                        msg = emoji_list[random.randint(0, len(emoji_list) - 1)]['value']

                        cookie_app_obj = CookieApp(userid, sid, device_id, smid, to_userid, msg)
                        obj = XhsTcp(cookie_app_obj, "login")
                        print('obj.ok8 -->', obj.ok8)
                        if obj.ok8:
                            # request_obj = Request("sms_register")
                            # name = str(int(time.time() * 1000))
                            # request_obj.init(name)
                            result_data = {
                                'blogger_id': blogger_id,
                                'blogger_name': blogger_name,
                                'blogger_img': blogger_img,
                                'device_data': json.dumps(device_data),

                                'machine_num': machine_name
                            }
                            self.request.update_user_info(result_data)
                            self.request.check_login_xhs(machine_name)
                        else:
                            self.request.delete_machine(machine_name)

                        # 获取接口使用情况
                        api_access_info = self.xhsapi.get_api_access_info()
                        print('api_access_info:' + api_access_info)

                        break

                    except ConnectionError:
                        pass
    #
    # def xhs_login_ck(self, machine_name):
    #     result_data = {
    #         'blogger_id': '',
    #         'blogger_name': '',
    #         'blogger_img': '',
    #         'device_data': '',
    #     }
    #     ck_data = self.get_xhs_user_ck()
    #     if ck_data:
    #         ck_data = json.loads(ck_data)
    #         self.init_xhsapi()
    #         self.xhsapi.set_register_user_data(ck_data)
    #
    #         userid = ck_data['blogger_data']['blogger_id']
    #         blogger_name = ck_data['blogger_data']['blogger_name']
    #         blogger_img = ck_data['blogger_data']['blogger_img']
    #         device_id = ck_data['device_id']
    #         smid = ck_data['smid']
    #         sid = ck_data['sid']
    #
    #         # 获取首页推荐
    #         home_feed = self.xhsapi.get_home_feed()
    #         to_userid = json.loads(home_feed)['data'][0]['user']['userid']
    #         print('to_userid -->', to_userid)
    #
    #         # to_userid = "5cb54ef500000000170043f6"  # 张聪小红书
    #         emoji_list = [
    #             {
    #                 'label': 'r_weixiao',
    #                 'value': '[微笑R]'
    #             },
    #             {
    #                 'label': 'haixiu',
    #                 'value': '[害羞R]'
    #             },
    #             {
    #                 'label': 'r_shiwang',
    #                 'value': '[失望R]'
    #             },
    #             {
    #                 'label': 'hanyan',
    #                 'value': '[汗颜R]'
    #             },
    #             {
    #                 'label': 'r_wa',
    #                 'value': '[哇R]'
    #             },
    #             {
    #                 'label': 'r_henaicha',
    #                 'value': '[喝奶茶R]'
    #             },
    #             {
    #                 'label': 'r_zipai',
    #                 'value': '[自拍R]'
    #             },
    #             {
    #                 'label': 'touxiao',
    #                 'value': '[偷笑R]'
    #             },
    #             {
    #                 'label': 'feiwen',
    #                 'value': '[飞吻R]'
    #             },
    #             {
    #                 'label': 'r_shihua',
    #                 'value': '[石化R]'
    #             },
    #             {
    #                 'label': 'xiaoku',
    #                 'value': '[笑哭R]'
    #             },
    #             {
    #                 'label': 'zan',
    #                 'value': '[赞R]'
    #             },
    #             {
    #                 'label': 'r_anzhongguancha',
    #                 'value': '[暗中观察R]'
    #             },
    #             {
    #                 'label': 'r_maibao',
    #                 'value': '[买爆R]'
    #             },
    #             {
    #                 'label': 'r_daxiao',
    #                 'value': '[大笑R]'
    #             },
    #             {
    #                 'label': 'sese',
    #                 'value': '[色色R]'
    #             },
    #             {
    #                 'label': 'shengqi',
    #                 'value': '[生气R]'
    #             },
    #             {
    #                 'label': 'kure',
    #                 'value': '[哭惹R]'
    #             },
    #             {
    #                 'label': 'mengmengda',
    #                 'value': '[萌萌哒R]'
    #             },
    #             {
    #                 'label': 'r_xieyan',
    #                 'value': '[斜眼R]'
    #             },
    #             {
    #                 'label': 'r_kelian',
    #                 'value': '[可怜R]'
    #             },
    #             {
    #                 'label': 'bishi',
    #                 'value': '[鄙视R]'
    #             },
    #             {
    #                 'label': 'r_zhoumei',
    #                 'value': '[皱眉R]'
    #             },
    #             {
    #                 'label': 'zhuakuang',
    #                 'value': '[抓狂R]'
    #             },
    #             {
    #                 'label': 'r_wulian',
    #                 'value': '[捂脸R]'
    #             },
    #             {
    #                 'label': 'r_paidui',
    #                 'value': '[派对R]'
    #             },
    #             {
    #                 'label': 'baji',
    #                 'value': '[吧唧R]'
    #             },
    #             {
    #                 'label': 'jingkong',
    #                 'value': '[惊恐R]'
    #             },
    #             {
    #                 'label': 'r_koubi',
    #                 'value': '[抠鼻R]'
    #             },
    #             {
    #                 'label': 'zaijian',
    #                 'value': '[再见R]'
    #             },
    #             {
    #                 'label': 'tanqi',
    #                 'value': '[叹气R]'
    #             },
    #             {
    #                 'label': 'r_shuijiao',
    #                 'value': '[睡觉R]'
    #             },
    #             {
    #                 'label': 'deyi',
    #                 'value': '[得意R]'
    #             },
    #             {
    #                 'label': 'r_chigua',
    #                 'value': '[吃瓜R]'
    #             },
    #             {
    #                 'label': 'fuqiang',
    #                 'value': '[扶墙R]'
    #             },
    #             {
    #                 'label': 'r_heishuwenhao',
    #                 'value': '[黑薯问号R]'
    #             },
    #             {
    #                 'label': 'r_huangjinshu',
    #                 'value': '[黄金薯R]'
    #             },
    #             {
    #                 'label': 'h_tushetou',
    #                 'value': '[吐舌头H]'
    #             },
    #             {
    #                 'label': 'h_chelian',
    #                 'value': '[扯脸H]'
    #             },
    #             {
    #                 'label': 'h_jingxia',
    #                 'value': '[惊吓H]'
    #             }
    #         ]
    #         msg = emoji_list[random.randint(0, len(emoji_list) - 1)]['value']
    #         print('msg -->', msg)
    #
    #         cookie_app_obj = CookieApp(userid, sid, device_id, smid, to_userid, msg)
    #         obj = XhsTcp(cookie_app_obj, "login")
    #         print('obj.ok8 -->', obj.ok8)
    #         # print("注册时间: %s" % time.strftime("%Y--%m--%d %H:%M:%S", time.localtime(int(register_time))))
    #
    #         device_data = self.xhsapi.get_register_user_data()
    #         if obj.ok8:
    #             # request_obj = Request("sms_register")
    #             # name = str(int(time.time() * 1000))
    #             # request_obj.init(name)
    #             result_data = {
    #                 'blogger_id': userid,
    #                 'blogger_name': blogger_name,
    #                 'blogger_img': blogger_img,
    #                 'device_data': json.dumps(device_data),
    #
    #                 'machine_num': machine_name
    #             }
    #             self.request.update_user_info(result_data)
    #             self.request.check_login_xhs(machine_name)
    #         else:
    #             self.request.delete_machine(machine_name)
    #
    #         # 获取接口使用情况
    #         api_access_info = self.xhsapi.get_api_access_info()
    #         print('api_access_info:' + api_access_info)
    #

    def xhs_login(self, machine_name):
        # if config.debug and config.RemoteComputerName == "test":
        #     username, password = ["chazhengen3@163.com", "7h47ayw"]
        # else:
        #     pass
        #     result = self.request.get_wb_user(machine_name)
        #     if not result:
        #         print("无可分配账号")
        #         return
        #     username, password = result
        #
        #     # exit()
        # print("username, password -->", username, password)
        self.init_xhsapi()
        self.xhsapi.init_new_device_params()
        register_smid_ret = self.xhsapi.register_smid()
        # print('register_smid_ret:' + register_smid_ret)

        smid = json.loads(register_smid_ret)['detail']['deviceId']
        print('smid:' + smid)
        self.xhsapi.set_smid(smid)

        # 激活用户
        # active_user_ret = self.xhsapi.active_user()
        # print('active_user_ret:' + active_user_ret)
        # success = json.loads(active_user_ret)['success']
        # if not success:
        #     crypt_method = json.loads(active_user_ret)['crypt_method']
        #     print('crypt_method: ' + crypt_method)
        #     self.xhsapi.set_crypt_method(crypt_method)
        #
        # active_user_ret = self.xhsapi.active_user()
        # print('active_user_ret:' + active_user_ret)
        #
        # # if 'data' not in json.loads(active_user_ret):
        # #     return False

        # # 设置session id
        # session_id = ''
        # active_json = json.loads(active_user_ret)
        # if 'data' in active_json:
        #     session_id = active_json['data']['session']
        #     print('session_id:' + session_id)

        session_id = ''
        active_user_result = self.xhsapi.active_user()
        print('active_user_result:' + active_user_result)
        active_user_result_data = json.loads(active_user_result)['data']
        if 'session' in active_user_result_data:
            session_id = active_user_result_data['session']
            print('session_id:' + session_id)
        else:
            return


        # # 微博登录
        # if len(session_id) == 0:
        #     print("微博登录")
        #     session_id = self.xhsapi.login_with_weibo_app(username, password)
        #
        # # 微博h5登录
        # if len(session_id) == 0:
        #     print("微博h5登录")
        #     session_id = self.xhsapi.login_with_weibo_h5(username, password)
        #     print('session_id:' + session_id)


        if len(session_id) == 0:
            print('session is empty, exit!')
            return False

        # 设置session_id
        self.xhsapi.set_session_id(session_id)

        # 获取登录用户信息
        login_user_info = self.xhsapi.get_login_userinfo()
        print('login_user_info:' + login_user_info)

        # result = self.xhsapi.set_tag_follow()
        # print(result)


        # exit()


        result = json.loads(login_user_info)['data']
        userid = result['userid']
        register_time = result['register_time']
        print('register_time -->', register_time)
        # print('session_id:' + session_id)
        # print('userid:' + userid)

        blogger_id = userid
        blogger_name = result['nickname']
        blogger_img = result['images']
        register_time = result['register_time']

        print(self.xhsapi.get_register_user_data())
        device_data = self.xhsapi.get_register_user_data()
        device_data['register_time'] = register_time
        result_data = {
            'blogger_id': blogger_id,
            'blogger_name': blogger_name,
            'blogger_img': blogger_img,
            'device_data': json.dumps(device_data),

            'machine_num': machine_name
        }
        self.request.update_user_info(result_data)

        self.request.delete_machine(machine_name)
        # 获取接口使用情况
        api_access_info = self.xhsapi.get_api_access_info()
        print('api_access_info:' + api_access_info)
        return

        # 获取首页推荐
        # home_feed = self.xhsapi.get_home_feed("homefeed.gaming_v3")
        home_feed = self.xhsapi.get_home_feed()
        # print('home_feed -->', home_feed)
        home_feed = json.loads(home_feed)
        print(home_feed, type(home_feed))
        try:
            to_userid = home_feed['data'][0]['user']['userid']
        except Exception:
            self.request.delete_machine(machine_name)
            return
        # print("to_userid -->", to_userid)
        # if len(self.to_userid_list) == 0:
        #     url = "http://81.70.192.137/api/v1/note/search?token=7h1vyqo7dfd&keyword=美妆"
        #     result = requests.get(url)
        #     for item in result.json()['data']:
        #         if item['model_type'] == "note":
        #             note_user_id = item['note']['user']['userid']
        #             self.to_userid_list.append(note_user_id)
        #
        # to_userid = self.to_userid_list.pop()




        # self.request.delete_machine(machine_name)
        # return
        # send_msg(device_data, blogger_id, blogger_name, blogger_img, to_userid)

        ck_data = {'blogger_data': [], 'device_data': device_data, 'blogger_id': blogger_id}
        userid = ck_data['blogger_id']
        sid = ck_data['device_data']['sid']
        device_id = ck_data['device_data']['device_id']
        smid = ck_data['device_data']['smid']

        # to_userid = "5cb54ef500000000170043f6"  # 张聪小红书
        emoji_list = [
            {
               'label': 'r_weixiao',
               'value': '[微笑R]'
            },
            {
               'label': 'haixiu',
               'value': '[害羞R]'
            },
            {
               'label': 'r_shiwang',
               'value': '[失望R]'
            },
            {
               'label': 'hanyan',
               'value': '[汗颜R]'
            },
            {
               'label': 'r_wa',
               'value': '[哇R]'
            },
            {
               'label': 'r_henaicha',
               'value': '[喝奶茶R]'
            },
            {
               'label': 'r_zipai',
               'value': '[自拍R]'
            },
            {
               'label': 'touxiao',
               'value': '[偷笑R]'
            },
            {
               'label': 'feiwen',
               'value': '[飞吻R]'
            },
            {
               'label': 'r_shihua',
               'value': '[石化R]'
            },
            {
               'label': 'xiaoku',
               'value': '[笑哭R]'
            },
            {
               'label': 'zan',
               'value': '[赞R]'
            },
            {
               'label': 'r_anzhongguancha',
               'value': '[暗中观察R]'
            },
            {
               'label': 'r_maibao',
               'value': '[买爆R]'
            },
            {
               'label': 'r_daxiao',
               'value': '[大笑R]'
            },
            {
               'label': 'sese',
               'value': '[色色R]'
            },
            {
               'label': 'shengqi',
               'value': '[生气R]'
            },
            {
               'label': 'kure',
               'value': '[哭惹R]'
            },
            {
               'label': 'mengmengda',
               'value': '[萌萌哒R]'
            },
            {
               'label': 'r_xieyan',
               'value': '[斜眼R]'
            },
            {
               'label': 'r_kelian',
               'value': '[可怜R]'
            },
            {
               'label': 'bishi',
               'value': '[鄙视R]'
            },
            {
               'label': 'r_zhoumei',
               'value': '[皱眉R]'
            },
            {
               'label': 'zhuakuang',
               'value': '[抓狂R]'
            },
            {
               'label': 'r_wulian',
               'value': '[捂脸R]'
            },
            {
               'label': 'r_paidui',
               'value': '[派对R]'
            },
            {
               'label': 'baji',
               'value': '[吧唧R]'
            },
            {
               'label': 'jingkong',
               'value': '[惊恐R]'
            },
            {
               'label': 'r_koubi',
               'value': '[抠鼻R]'
            },
            {
               'label': 'zaijian',
               'value': '[再见R]'
            },
            {
               'label': 'tanqi',
               'value': '[叹气R]'
            },
            {
               'label': 'r_shuijiao',
               'value': '[睡觉R]'
            },
            {
               'label': 'deyi',
               'value': '[得意R]'
            },
            {
               'label': 'r_chigua',
               'value': '[吃瓜R]'
            },
            {
               'label': 'fuqiang',
               'value': '[扶墙R]'
            },
            {
               'label': 'r_heishuwenhao',
               'value': '[黑薯问号R]'
            },
            {
               'label': 'r_huangjinshu',
               'value': '[黄金薯R]'
            },
            {
               'label': 'h_tushetou',
               'value': '[吐舌头H]'
            },
            {
               'label': 'h_chelian',
               'value': '[扯脸H]'
            },
            {
               'label': 'h_jingxia',
               'value': '[惊吓H]'
            }
        ]
        msg = emoji_list[random.randint(0,len(emoji_list) - 1)]['value']
        # msg = str(time.time() * 1000)
        print('msg -->', msg)
        # to_userid = "60e95542000000002002c1a5"

        cookie_app_obj = CookieApp(userid, sid, device_id, smid, to_userid, msg)
        obj = XhsTcp(cookie_app_obj, "login")
        print('obj.ok8 -->', obj.ok8)
        print("注册时间: %s" % time.strftime("%Y--%m--%d %H:%M:%S", time.localtime(int(register_time))))
        if obj.ok8:
            print("注册成功")
            # exit()
            # request_obj = Request("sms_register")
            # name = str(int(time.time() * 1000))
            # request_obj.init(name)
            result_data = {
                'blogger_id': blogger_id,
                'blogger_name': blogger_name,
                'blogger_img': blogger_img,
                'device_data': json.dumps(device_data),

                'machine_num': machine_name
            }
            self.request.update_user_info(result_data)
            self.request.check_login_xhs(machine_name)
        else:
            # exit()
            self.request.delete_machine(machine_name)
            pass

        # 获取接口使用情况
        api_access_info = self.xhsapi.get_api_access_info()
        print('api_access_info:' + api_access_info)

    # 发送消息
    def send_msg(self, machine_name):

        task_data = self.request.get_message_task(machine_name)
        # print("task_data -->", task_data)
        if task_data:
            self.switch_ip()
            # print('task_data -->', task_data)
            ck_data = self.request.get_blogger_list(machine_name)
            # print('ck_data -->', ck_data)
            # userid = "5f4b02f90000000001006277"
            # sid = "session.1598752227482778345076"
            # device_id = "d1c7d312-f226-4fc1-acb2-9ad11826b5cd"
            # smid = "20200830095024dde1263afe41c820e24ee045f06e569c0186de0cc4b6e6ae"
            # to_userid = "5ef0c195000000000101df16"
            # msg = "你想了解的这款现在有折扣，你可以+v  15641 0072 43 我发给你看看，部分包包有五折，我们支持 货到付款。"
            userid = ck_data['blogger_id']
            sid = ck_data['device_data']['sid']
            device_id = ck_data['device_data']['device_id']
            smid = ck_data['device_data']['smid']
            to_userid = task_data['blogger_url'].split('/')[-1]
            msg = task_data['message']
            task_id = task_data['task_id']
            cookie_app_obj = CookieApp(userid, sid, device_id, smid, to_userid, msg)
            obj = XhsTcp(cookie_app_obj, "send")
            if obj.user_auth:
                self.request.post_message_task(task_id)
            elif obj.disabled:  # 账号被封禁
                self.request.delete_machine(machine_name)
            else:
                print("账号被顶,重新登录")
                self.request.delete_machine(machine_name)

            return True

    # 获取新消息
    def get_new_msg(self, machine_name):
        ck_data = self.request.get_blogger_list(machine_name)
        # print('ck_data -->', ck_data)

        if ck_data:
            # print('ret -->', ret)
            # [{"blogger_id": "5c7a0ab60000000010029c2e"}]

            blogger_data = ck_data['blogger_data']
            device_data = ck_data['device_data']
            if len(blogger_data) > 0:
                print("===================== 获取消息列表 =====================")
                print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
                for blogger in blogger_data:
                    # self.sleep_random()
                    blogger_id = blogger['blogger_id']
                    # self.xhsapi.set_register_user_data(device_data)
                    self.xhsapi_690.set_register_user_data(device_data)
                    ret = self.xhsapi_690.get_message(blogger_id)
                    # print('ret -->', ret)
                    result_dict = json.loads(ret)

                    if result_dict['success']:
                        # print("result_dict['data'] -->", result_dict['data'])
                        data = {
                            'msg_data': json.dumps(result_dict['data']),
                            'blogger_id': blogger_id,
                            'machine_num': machine_name,
                        }
                        ret = self.request.rsync_msg(data)
                    else:
                        if result_dict['error_message'] == "用户校验失败":
                            self.xhs_login(machine_name)
                return True


def start():
    # remote_computer_name = config.RemoteComputerName
    remote_computer_name = None
    cid = config.CID

    obj = XhsShixin(remote_computer_name)

if __name__ == '__main__':

    # start()
    # exit()

    start_window = 10
    executor = ThreadPoolExecutor(max_workers=start_window)
    print(executor)

    task_list = []
    for i in range(start_window):
        future = executor.submit(start)
        future.i = i
        task_list.append(future)

    while True:
        new_task_list = []
        # print('')
        for task in task_list:

            if task.done():
                # print("task.done() -->", task.done())
                # print('i -->', task.i)
                print("==============================>启动新的线程", task.i)
                future = executor.submit(start)
                future.i = task.i
                new_task_list.append(future)
            else:
                new_task_list.append(task)
        task_list = new_task_list
        # print("/////////////////////////////task_list_len -->", len(task_list))
    # remote_computer_name = config.RemoteComputerName
    # cid = config.CID
    # # obj = XhsShixin(remote_computer_name)
    #
    # # obj = XhsShixin(remote_computer_name)
    # # device_data = {"device_id": "24b72b11-ea39-4172-9cac-6c5ec7e6b45f", "smid": "2020083108111918f1746c56fc657889b23b505457bb8001577640976f051e", "sid": "session.1598832714642135150397", "fid": "1598832667104b5382889a82ed20d27623b2d40c965a", "crypt_method": "5f97953f0fa1cb58"}
    # # obj.xhsapi.set_register_user_data(device_data)
    # # result = obj.xhsapi.get_message("5cb54ef500000000170043f6")
    # # print('result -->', result)
    #
    # # obj = XhsShixin(remote_computer_name, cid)
    # # if not config.t:
    # #     t = input("选择账号类型:手机号请输入1, 微博请输入2 >>>")
    # #     if t not in ['1', '2']:
    # #         t = 1
    # # else:
    # #     t = config.t
    # # obj = XhsShixin(remote_computer_name)
    # # exit()
    # if config.debug:
    #     obj = XhsShixin(remote_computer_name)
    # else:
    #     while True:
    #         try:
    #             obj = XhsShixin(remote_computer_name)
    #         except:
    #             pass